package com.app.messenger;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


    private Button mBtn;

    private Handler mClientHandler;
    private Messenger mClientMessenger;
    private Messenger mServiceMessenger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBtn = this.findViewById(R.id.btn_start);

        mClientHandler = new ClientHandler();
        mClientMessenger = new Messenger(mClientHandler);


        this.bindService(new Intent(this, RemoteService.class), new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                mServiceMessenger = new Messenger(iBinder);

            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        }, BIND_AUTO_CREATE);
    }


    public void remoteClick(View view) {
        Message msg = Message.obtain(null, 1);
        msg.replyTo = mClientMessenger;
        try {
            mServiceMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    static class ClientHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            int value = msg.arg1;
            Log.e("wanghaha", "value:" + value);
        }
    }
}
